package com.unionftech.common.utils

import android.util.Base64
import java.security.KeyFactory
import java.security.interfaces.RSAPublicKey
import java.security.spec.X509EncodedKeySpec
import javax.crypto.Cipher

object SignUtils {
    private const val ALGORITHM = "RSA"

    /**
     * 从字符串中加载公钥
     */
    fun loadPublicKeyByStr(publicKeyStr: String): RSAPublicKey? {
        try {
            val buffer = Base64.decode(publicKeyStr, Base64.NO_WRAP or Base64.NO_PADDING)
            val keyFactory = KeyFactory.getInstance(ALGORITHM)
            val keySpec = X509EncodedKeySpec(buffer)
            return keyFactory.generatePublic(keySpec) as RSAPublicKey
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 公钥加密
     */
    fun encrypt(rsaPublicKey: RSAPublicKey?, plainTextData: ByteArray): String? {
        if (rsaPublicKey == null) {
            return null
        }
        try {
            val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
            cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey)
            val output = cipher.doFinal(plainTextData)
            return Base64.encodeToString(output, Base64.NO_WRAP or Base64.NO_PADDING)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }
}